import React, { useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { NavBar } from "antd-mobile";
import "./Liao.css";
import { PullToRefresh, List } from "antd-mobile";
import { sleep } from "antd-mobile/es/utils/sleep";
import { useSelector } from "react-redux";
import goeasy from './Gieasy'

const Liao = () => {
    var im = goeasy.im;
    let location = useLocation()
    let { juese, usename,usertu } = location.state.item
    // console.log(location.state.item);
    let name = useSelector((store) => store.list)
    // let name = JSON.parse(sessionStorage.getItem('user'))
    // console.log(name)
    let [list, setlist] = useState([])
    let navi = useNavigate()
    let [nowtext, setnowtext] = useState('')
    let [len, setlen] = useState(8)

    const Lianj = () => {
        goeasy.connect({
            id: name[0]._id,
            data: { "avatar": '/www/xxx.png', "nickname": "Neo" },
            onSuccess: function () {//连接成功
                Lishi()
            },
            onFailed: function (error) {//连接失败
            },
            onProgress: function (attempts) { //连接或自动重连中
            }
        })
    }
    const SiLiao = () => {
        //创建消息, 内容最长不超过3K，可以发送字符串，对象和json格式字符串
        let textMessage = im.createTextMessage({
            text: nowtext, //消息内容
            to: {
                type: goeasy.IM_SCENE.PRIVATE,   //私聊还是群聊，群聊为GoEasy.IM_SCENE.GROUP
                id: juese[0], //接收方用户id
                data: { "avatar": "/www/xxx.png", "nickname": "Neo" } //接收方用户扩展数据, 任意格式的字符串或者对象，用于更新会话列表conversation.data
            }
        });
        // 发送消息
        im.sendMessage({
            message: textMessage,
            onSuccess: function (message) { //发送成功
                Lishi()
            },
            onFailed: function (error) { //发送失败
            }
        });

    }
    var onPrivateMessageReceived = function (message) {
        Lishi()
    };
    const JianTingI = () => {
        //监听和接收单聊消息
        im.on(goeasy.IM_EVENT.PRIVATE_MESSAGE_RECEIVED, onPrivateMessageReceived);
    }
    useEffect(() => {
        Lianj()
        JianTingI()
    }, [])
    const send = () => {
        SiLiao()
        setnowtext('')
    }
    //跳转
    const back1 = () => {
        navi('/app/xiaoxi')
    }
    const Lishi = () => {
        //获取历史记录
        im.history({
            id: juese[0],//用户id或者群id
            type: goeasy.IM_SCENE.PRIVATE, //群聊：GoEasy.IM_SCENE.GROUP, 客服：GoEasy.IM_SCENE.CS,
            limit: 10, //可选项，返回的消息条数，默认为10条，最多30条
            onSuccess: function (result) {
                //成功的
                setlist(result.content)
                
            },
            onFailed: function (error) {
                //失败的
            },
        });
    }
    
    return (
        <div id='ref'>
            <div className="header_50">
                <NavBar onBack={back1}>与{usename}聊天中</NavBar>
            </div>
            <div className="header_51"></div>
            <div className="header_52">
                <PullToRefresh
                    onRefresh={async () => {
                        await sleep(1000);
                        setlen(len + 5);
                    }}
                >
                    <List style={{ minHeight: "90vh" }}>
                        {list.map((item, index) => {
                            return (
                                <div
                                    key={index}
                                    className={
                                        item.receiverId
                                        == name[0]._id
                                        ? "header_53" : "header_54"
                                    }
                                >
                                    {item.receiverId == name[0]._id ? <img src={name[0].usertu} /> : <img src={usertu} />}
                                    <span className="header_55">{item.payload.text}</span>
                                </div>
                            );
                        })}
                        <div id="mao"></div>
                    </List>
                </PullToRefresh>
            </div>
            <div className="header_56">
                <p>
                    <input
                        type="text"
                        id='textInput'
                        value={nowtext}
                        onChange={(e) => {
                            setnowtext(e.target.value);
                        }}
                        onKeyDown={(e) => {
                            if (e.keyCode == 13) {
                                send();
                            }
                        }}
                    />
                </p>
                <p>
                    <button
                        onClick={() => {
                            send();
                        }}
                    >
                        发送
                    </button>
                </p>
            </div>
        </div>
    )
}

export default Liao;